package com.example.lunckypanlib.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.nfc.Tag;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Range;
import android.util.TypedValue;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.animation.AccelerateDecelerateInterpolator;

import com.example.lunckypanlib.R;

import java.util.Random;

/**
 * 转盘Ui
 */
public class RotaryView extends SurfaceView implements SurfaceHolder.Callback, Runnable {
    private static final String TAG = "RotaryView";
    private SurfaceHolder mSurfaceHolder;
    private Canvas mCanvas;
    /**
     * 用于surfaceview绘制的子线程
     */
    private Thread mThread;
    /**
     * 控制子线程开关
     */
    private boolean isRunning;

    /**
     * 背景
     */
    private Bitmap mBgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rotary_background);
    private Bitmap mArrowBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rotary_arrow);
    private Bitmap mTableBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rotary_table);
    private ValueAnimator animator;
    private PaintFlagsDrawFilter filter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

    /**
     * 整个盘块的直径
     */
    private int mRadius;
    /**
     * 绘制盘块的画笔
     */
    private Paint mArcPaint;
    /**
     * 盘块滚动的速度
     */
    private float mSpeed = 3f;
    private boolean start = false;
    /**
     * 转盘的中心位置
     */
    private int mCenterX;
    private int mCenterY;

    /**
     * volatile保证线程间的可见性
     */
    private volatile float mStartAngle = 0;

    /**
     * 判断是否点击了停止按钮
     */
    private boolean isShouldEnd = false;

    /**
     * 设置单次绘制最低时间，如果在该时间内绘制完成，让子线程sleep到改时间结束
     * 这样防止了线程绘制频繁，先消耗性能的问题
     */
    private long mOneTimeMinMillionSeconds = 50;

    private int mDifferSpeed = 1;// 调用停止后递减的速度差值 要大于0

    private RotaryListenner rotaryListenner;

    public void setRotaryListenner(RotaryListenner rotaryListenner) {
        this.rotaryListenner = rotaryListenner;
    }

    public interface RotaryListenner{
        void rotaryReward(int reward);
    }

    public RotaryView(Context context) {
        super(context);
        init(context);
    }

    public RotaryView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public RotaryView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        mSurfaceHolder = this.getHolder();
        // 管理surfaceview的生命周期
        mSurfaceHolder.addCallback(this);
        // 能够获取焦点
        this.setFocusable(true);
        this.setFocusableInTouchMode(true);
        // 保持常亮
        this.setKeepScreenOn(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        //直径
        mRadius = (int) (width / 1.8f);
        // 中心点
        mCenterX = width / 2;
        mCenterY = height / 2;
        setMeasuredDimension(width, height);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        // 初始化盘块画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);
        draw();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        isRunning = false;
    }

    @Override
    public void run() {
        /**
         * 不断的进行绘制
         */
        while (isRunning) {
            draw();
        }
    }

    private void draw() {
        try {
            mCanvas = mSurfaceHolder.lockCanvas();
            if (mCanvas != null) {
                // 绘制
                drawBg();
                drawTable();
                drawArrow();
            }
        } catch (Exception e) {
            //e.printStackTrace();
        } finally {
            if (mCanvas != null) {
                mSurfaceHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }


    /**
     * 绘制背景
     */
    private void drawBg() {
        mCanvas.setDrawFilter(filter);
        //透明背景
        mCanvas.drawColor(0x00FFFFFF);
        //画背景
        mCanvas.drawBitmap(mBgBitmap, null,
                new Rect(0, 0, getMeasuredWidth(),
                        getMeasuredHeight()), mArcPaint);
    }

    //当前的旋转角度
    private float rotate = 0f;
    private float offset = 0f;
    private float lastOffset = 0f;
    //变速增量
    private float rotateIncrement = 1.0f;

    private void drawTable() {
        if (start) {
            rotate = rotate + mSpeed * rotateIncrement;
        }
        Log.i(TAG, "drawTable: " + rotate);
        drawRotateBitmap(mCanvas, mArcPaint, mTableBitmap, rotate);

    }

    /**
     * 绘制指针
     */
    private void drawArrow() {
        //宽高,直径的五分之一
        int witdh = mRadius / 5;
        int height = mRadius / 5;
        int left = mCenterX - witdh / 2;
        int top = mCenterY - height / 2;
        int right = mCenterX + witdh / 2;
        int bottom = mCenterY + height / 2;
        mCanvas.drawBitmap(mArrowBitmap, null, new Rect(left, top, right, bottom), mArcPaint);
    }

    /**
     * 绘制自旋转位图
     *
     * @param canvas
     * @param paint
     * @param bitmap   位图对象
     * @param rotation 旋转度数
     * @param posX     在canvas的位置坐标
     * @param posY
     */
    private Matrix matrix = new Matrix();

    private void drawRotateBitmap(Canvas canvas, Paint paint, Bitmap bitmap,
                                  float rotation) {
        matrix.reset();
        //图片的半径
        int radius = bitmap.getWidth() / 2;
        int centerX = mCenterX - radius;
        int centerY = mCenterY - radius;
        //先挪动图片半径的一般，让旋转中心点位于图片中央
        matrix.postTranslate(-radius, -radius);
        //再旋转
        matrix.postRotate(rotation);
        //再移回原来的位置，并增加移动增量
        matrix.postTranslate(centerX + radius, centerY + radius);
        canvas.drawBitmap(bitmap, matrix, paint);
    }


    public void animtorStart() {
        if (start) {
            return;
        }
        mTableBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.rotary_table);
        offset = new Random().nextInt(360);
        rotate = offset;
        Log.i(TAG, "animtorStart: offset" + offset);
        Log.i(TAG, "animtorStart: rotate" + rotate);
        isRunning = true;
        start = true;
        mThread = new Thread(this);
        mThread.start();
        animator = ValueAnimator.ofFloat(1f, 8f, 15f, 20f, 10f, 5f, 1f, 0.05f);
        animator.setDuration(8 * 1000).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float) valueAnimator.getAnimatedValue();
                rotateIncrement = value;
            }

        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                start = false;
                isRunning = false;
                int reward = witchReward(rotate);
                notifyReward(reward);
                Log.i(TAG, "onAnimationEnd: " + rotate);
                Log.i(TAG, "reward: " + reward);
            }
        });
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
    }

    private void notifyReward(int reward){
        if(rotaryListenner!=null){
            rotaryListenner.rotaryReward(reward);
        }
    }
    public void animtorEnd() {
        animator.end();
    }


    private int witchReward(float rotates) {
        Log.i(TAG, "witchReward:rotates " + rotates);
        float rotate = (rotates) % 360f;
        //起始角度为0, 此时-30f-30f 为二张，
        if (0 < rotate && rotate <= 30) {
            return 2;
        }
        if (30 < rotate && rotate <= 90) {
            return 1;
        }

        if (90 < rotate && rotate <= 150) {
            return 3;
        }
        if (150 < rotate && rotate <= 210) {
            return 1;
        }
        if (210 < rotate && rotate <= 270) {
            return 2;
        }
        if (270 < rotate && rotate <= 330) {
            return 1;
        }
        if (330 < rotate && rotate <= 360) {
            return 2;
        }
        return 1;
    }
}
